package cn.kgc.vue.controller;

import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/9/27
 * @description 权限模块
 */
@RestController
@RequestMapping("permission")
@Slf4j
public class PermissionController {

    @Resource
    private PermissionService permissionService;


    // 删除权限信息
    @DeleteMapping("delete/{id}")
    public ResponseResult deletePermission(@PathVariable("id") Integer id) {
        log.error("id = {}",id);
        return permissionService.deletePermission(id);
    }

    // 根据id获取权限信息
    @GetMapping("one/{id}")
    public ResponseResult getOnePermission(@PathVariable("id") Integer id) {

        Permission permission = permissionService.getById(id);
        Integer pid = permission.getPid();

        Permission parentPermission = permissionService.getById(pid);
        String title = null;
        if (ObjectUtils.isNotNull(parentPermission)) {
            title = parentPermission.getTitle();
        }

        return ResponseResult.success()
                .data("permission", permission)
                .data("parentTitle", title);
    }

    // 添加权限
    @PostMapping("add")
    public ResponseResult addPermission(@RequestBody Permission permission) {
        log.error("permisson={}", permission);
        permissionService.saveOrUpdate(permission);
        return ResponseResult.success();
    }

    @GetMapping("list")
    public ResponseResult permissionList() {

        List<Permission> list = permissionService.list();
        return ResponseResult.success().data("permissionList", list);
    }


    @GetMapping("treeData")
    public ResponseResult treeData() {
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.select(Arrays.asList("id", "pid", "title"));

        List<Permission> list = permissionService.list(permissionQueryWrapper);

        return ResponseResult.success().data("permissionList", list);
    }
}
